package com.gaoqi.mq.workQueue;

import com.gaoqi.mq.utils.RabbitMQ;
import com.rabbitmq.client.*;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

@Slf4j
public class Consumer1 {

    //rabbitmq 工作模式 测试消费消息
    public void workConsume() throws IOException {
        //获取mq 连接对象
        Connection rabbitConnection = RabbitMQ.getRabbitConnection();
        //获取通道对象
        Channel consumerChannel = rabbitConnection.createChannel();

        //通道绑定设置参数
        consumerChannel.queueDeclare("work", true, false, false, null);

        //消息确认每次只确认1个
        consumerChannel.basicQos(1);

        //消费者消费 参数1 队列名 参数2 是否消息消费自动确认 参数3 消费时 回调接口
        consumerChannel.basicConsume("work", false, new DefaultConsumer(consumerChannel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                //消费者睡眠线程1秒
                try {
                    Thread.sleep(800);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                log.info("消费者——1 消费:{}", new String(body));
                //手动开启确认消息消费
                consumerChannel.basicAck(envelope.getDeliveryTag(), false);
            }
        });
    }

    public static void main(String[] args) throws IOException {
        new Consumer1().workConsume();
    }
}
